package com.zahb.qadx.ui.activity;

import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.AssessmentBean;
import com.zahb.qadx.model.StudyRecordBean;
import com.zahb.qadx.model.TrainInfoBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.adapter.AssessmentAdapter;
import com.zahb.qadx.ui.adapter.StudyRecordAdapter;
import com.zahb.qadx.ui.adapter.TrainRecordAdapter;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.Tips;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class ArchivesRecordActivity extends BaseActivity {


    @BindView(R.id.tvLeft)
    TextView tvLeft;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.rlTop)
    RelativeLayout rlTop;
    @BindView(R.id.recyc)
    RecyclerView recyc;


    List<TrainInfoBean.ListEntity> trainRecordList = new ArrayList<>();
    BaseQuickAdapter adapter = new TrainRecordAdapter(R.layout.item_train_record, trainRecordList);

    List<StudyRecordBean.ListEntity> studyRecordList = new ArrayList<>();

    List<AssessmentBean.ListEntity> assessmentList = new ArrayList<>();

    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    @Override
    protected int getLayout() {
        return R.layout.activity_archives_record;
    }

    @Override
    protected void initViews() {
        type = getIntent().getIntExtra("type", 0);
        mUnbinder = ButterKnife.bind(this);


        if (type == 2) {
            adapter = new TrainRecordAdapter(R.layout.item_train_record, trainRecordList);
        }
        if (type == 3) {
            adapter = new StudyRecordAdapter(R.layout.item_study_record, studyRecordList);
        }
        if (type == 4) {
            adapter = new AssessmentAdapter(R.layout.item_assessment_record, assessmentList);
        }

        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        adapter.setEmptyView(emptyView);

        recyc.setAdapter(adapter);
        recyc.setLayoutManager(new LinearLayoutManager(this));

        adapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            if((startPage+1)>totalPage){
                adapter.getLoadMoreModule().loadMoreEnd();
            }else{
                startPage=startPage+1;
                getData();
            }
        });

        getData();
        showSkeleton();
    }

    private void showSkeleton() {
        mSkeletonScreen = Skeleton.bind(recyc)
                .adapter(adapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_record_skeleton)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    int type = 0;

    @Override
    protected int getTitleStringRes() {
        type = getIntent().getIntExtra("type", 0);
        if (type == 2) {
            return R.string.train_record;
        }
        if (type == 3) {
            return R.string.study_record;
        }
        if (type == 4) {
            return R.string.assessment_record;
        }
        return R.string.train_record;
    }


    int startPage = 1;
    int pageSize = 5;


    int totalPage = 1;

    public void getData(){
        if(BaseApplication.getContext().getDataLogin()==null){
            return;
        }
        if (type == 2) {
            Map<String, Object> params = new HashMap<>();
            params.put("startPage", startPage);
            params.put("pageSize", pageSize);
            params.put("userId", BaseApplication.getContext().getDataLogin().getUser().getId());
            params.put("rootOrgId", BaseApplication.getContext().getDataLogin().getCurrentOrg());

            Gson mGson = new Gson();
            String json = mGson.toJson(params);
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
            addDisposable(RetrofitService.getNetService()
                    .getUserTrainInfoList(body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        adapter.getLoadMoreModule().loadMoreComplete();
                        if (response.getStatusCode() == 200) {
                            trainRecordList.addAll(response.getData().getList());
                            adapter.notifyDataSetChanged();
                            totalPage=response.getData().getPages();
                        } else {
                            showBindToast(response.getErrorInfo());
                        }
                        hideSkeleton();
                    }, throwable -> {
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                        hideSkeleton();
                    }));
        }

        if (type == 3) {

            addDisposable(RetrofitService.getNetService()
                    .getCourseLearnRecordList(startPage,pageSize,
                            BaseApplication.getContext().getDataLogin().getUser().getId()
                    ,"","","")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        adapter.getLoadMoreModule().loadMoreComplete();
                        if (response.getStatusCode() == 200) {
                            studyRecordList.addAll(response.getData().getList());
                            adapter.notifyDataSetChanged();
                            totalPage=response.getData().getPages();
                        } else {
                            showBindToast(response.getErrorInfo());
                        }
                        hideSkeleton();
                    }, throwable -> {
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                        hideSkeleton();
                    }));

        }

        if (type == 4) {

            addDisposable(RetrofitService.getNetService()
                    .assessmentrecord(startPage,pageSize)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        adapter.getLoadMoreModule().loadMoreComplete();
                        if (response.getStatusCode() == 200) {
                            assessmentList.addAll(response.getData().getList());
                            adapter.notifyDataSetChanged();
                            totalPage=response.getData().getPages();
                        } else {
                            showBindToast(response.getErrorInfo());
                        }
                        hideSkeleton();
                    }, throwable -> {
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                        hideSkeleton();
                    }));

        }
    }

}
